package com.strat.searcher.lucene.indexing;

import java.io.File;

public class Indexer {

    private IndexWriterable writer;
    private final String PARSABLE_FILE_ENDING = ".txt";

    public Indexer(File indexDir) {
        writer = new IndexWriterWrapper(indexDir);
    }

    public Indexer(IndexWriterable writer) {
        this.writer = writer;
    }

    public int index(File dataDir) {
        File[] files = dataDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            File f = files[i];
            if (isFileIndexable(f)) {
                indexFile(f);
            }
        }
        return writer.numDocs();
    }

    private boolean isFileIndexable(File f) {
        return (!f.isDirectory()) && (!f.isHidden()) && f.exists()
                && f.canRead() && acceptFile(f);
    }

    private boolean acceptFile(File f) {
        return f.getName().endsWith(PARSABLE_FILE_ENDING);
    }

    private void indexFile(File f) {
        writer.addDocument(f);
    }

    public void close() {
        writer.close();
    }

}